/**
 * 
 */
package com.cgbsoft.financial;

import java.math.BigDecimal;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.cgbsoft.financial.common.ConfigurationManager;
import com.cgbsoft.financial.dao.MyTransactionDB;
import com.cgbsoft.financial.dao.TransactionFileManager;
import com.cgbsoft.financial.domain.MyTransaction;

/**
 * @author CX
 *
 */
public class TransactionModify extends Activity {
	
	static final int DATE_DIALOG_ID = 0; 
	
	private EditText transactionSummary, transactionMoney;
	private TextView transactiondate, transactionId, transactionCatagory;
	private Button transationSaveButton;
	private RadioGroup transactionType;
	
	private static MyTransaction myTransaction;
	
	String[] outcomeselectOptionList={"日常", "生活", "节日", "娱乐", "家庭", "教育", "其他"};
	String[] incomeSelectOptionList={"工资", "奖金", "提成", "报销", "营业", "分红", "股票", "基金", "利息", "其他"};
	
	public ProgressDialog pd_loading;//进度条对话框
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.transaction_modify);
        
        transactiondate = (TextView)findViewById(R.id.transaction_date);
        transactionSummary = (EditText)findViewById(R.id.transaction_summary);
        transactionMoney = (EditText)findViewById(R.id.transaction_money);
        transactionType = (RadioGroup)findViewById(R.id.transaction_type);
        transationSaveButton = (Button)findViewById(R.id.transation_save_button);
        transactionCatagory = (TextView)findViewById(R.id.transaction_catagory);
        
        transactiondate.setOnClickListener(clickListener);
        transactionType.setOnClickListener(clickListener);
        transationSaveButton.setOnClickListener(clickListener);
        transactionCatagory.setOnClickListener(clickListener);
        
        findViewById(R.id.transation_cancel_button).setOnClickListener(clickListener);
        
        //初始化数据
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
        	String money = bundle.getString("transactionMoney");
        	
        	transactiondate.setText(bundle.getString("transactiondate"));
            transactionSummary.setText(bundle.getString("transactionSummary"));
            transactionMoney.setText(money.substring(1, money.length()));
            transactionCatagory.setText(bundle.getString("transactionCatagory"));
            if ('+' == money.charAt(0)) {
            	transactionType.setTag(((RadioButton) findViewById(R.id.income)).getText().toString());
            	((RadioButton) findViewById(R.id.income)).setChecked(true);
        	} else {
        		transactionType.setTag(((RadioButton) findViewById(R.id.outcome)).getText().toString());
        		((RadioButton) findViewById(R.id.outcome)).setChecked(true);
        	}
            transactionType.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    			@Override
    			public void onCheckedChanged(RadioGroup arg0, int checkId) {
    				switch(checkId) {
    				case R.id.outcome:
    					transactionType.setTag(((RadioButton) findViewById(R.id.outcome)).getText().toString());
    					transactionCatagory.setText(outcomeselectOptionList[0]);
    					break;
    				case R.id.income:
    					transactionType.setTag(((RadioButton) findViewById(R.id.income)).getText().toString());
    					transactionCatagory.setText(incomeSelectOptionList[0]);
    					break;
    				default:
    					break;
    				}
    			}
        	});
            
            //保存myTransaction
            myTransaction = new MyTransaction();
            myTransaction.setId(Integer.valueOf(bundle.getString("transactionId")));
            myTransaction.setdDate(bundle.getString("transactiondate"));
            myTransaction.setsSubject(bundle.getString("transactionSummary"));
            myTransaction.setiSum(bundle.getString("transactionMoney"));
            myTransaction.setcCatagory(bundle.getString("transactionCatagory"));
        }
        
        pd_loading = new ProgressDialog(this);
		pd_loading.setCancelable(true);
    }
    
    
    
    private void modifyTransation() {
    	
    	final String transactiondateValue = transactiondate.getText().toString();
    	final String transactionSummaryValue = transactionSummary.getText().toString();
		String transactionMoneyValue = transactionMoney.getText().toString();
		final String transactionTypeValue = transactionType.getTag().toString();
		final String transactionCatagoryValue = transactionCatagory.getText().toString();
		
		BigDecimal transactionMoneyDecimal = new BigDecimal(transactionMoneyValue).multiply(new BigDecimal("100"));
		transactionMoneyValue = String.valueOf(transactionMoneyDecimal.intValue());
		
		myTransaction.setdDate(transactiondateValue);
		myTransaction.setsSubject(transactionSummaryValue);
		myTransaction.setiSum(("收入".equalsIgnoreCase(transactionTypeValue) ? "+" : "-") + transactionMoneyValue);
		myTransaction.setcCatagory(transactionCatagoryValue);
    	
		if (transactionMoneyValue != "" && transactionSummaryValue != "") {
			saveTransactionToXml(myTransaction);
		}
    }
    
    private void saveTransactionToXml(final MyTransaction myTransaction) {
    	pd_loading.setMessage("修改中...");
    	pd_loading.show();
    	new Thread(
				new Runnable() { 
					public void run() { 
						//添加到xml中去
						boolean returnInd = false;
						
						if (ConfigurationManager.getInstance(TransactionModify.this).getBooleanConfig(ConfigurationManager.IF_DB_STORE, false)) {
							//添加到数据库
							MyTransactionDB.updateMyTransaction(TransactionModify.this, myTransaction);
							returnInd = true;
						} else {
							returnInd = TransactionFileManager.modifyTransaction(myTransaction);
						}
				        
				        if (pd_loading.isShowing()) {
				        	pd_loading.dismiss();
				        }
				        
				        //跳回主界面
				        if (returnInd) {
							TransactionModify.this.finish();
				        }
					}
				}).start();	
    }
    
    OnClickListener clickListener= new OnClickListener() { 
    	@Override
    	public void onClick(View v) { 
    		switch (v.getId()) {
    		case R.id.transaction_catagory: {
    			String[] tempOptionList = outcomeselectOptionList;
    			if ("收入".equalsIgnoreCase(transactionType.getTag().toString())) {
    				tempOptionList = incomeSelectOptionList;
    			}
    			final String[] selectOptionList = tempOptionList;
	  	          new AlertDialog.Builder(TransactionModify.this)
	  	            .setTitle("类别选择")
	  	            .setItems(
	  	            		selectOptionList,
	  	            		new DialogInterface.OnClickListener() {
			    	              public void onClick(DialogInterface dialog, int whichcountry) {                                      
			    	            	  transactionCatagory.setText(selectOptionList[whichcountry]);
			    	              }
			    	            })
	  	            .setNegativeButton(
	  	            		"取消", 
	  	            		new DialogInterface.OnClickListener() { 
			    	              public void onClick(DialogInterface d, int which) { 
			    	                d.dismiss(); 
			    	              }
			    	            })
	  	            .show();
	  	          break;
    		}
    		case R.id.transaction_date: {//日期选择
    			showDialog(DATE_DIALOG_ID);
    			break;
    		}
    		case R.id.transation_save_button: {//添加消费
    			modifyTransation();
    	        break;
    		}
    		case R.id.transation_cancel_button: {//取消
    			TransactionModify.this.finish();
    			break;
    		}
    		default:
    			break;
    		}
    	}
	};
	
	//日期选择
	@Override    
    protected Dialog onCreateDialog(int id) {     
        switch (id) {     
        case DATE_DIALOG_ID: 
        	String tday = transactiondate.getText().toString();
            return new DatePickerDialog(this,     
                        mDateSetListener,   
                        Integer.valueOf(tday.substring(0, 4)), 
                        Integer.valueOf(tday.substring(5, 7)) - 1, 
                        Integer.valueOf(tday.substring(8, 10)));     
        }
        return null;
    }   
	//点击事件
	private DatePickerDialog.OnDateSetListener mDateSetListener =     
        new DatePickerDialog.OnDateSetListener() {     
    
            public void onDateSet(DatePicker view, int year,      
                                  int monthOfYear, int dayOfMonth) {    
                transactiondate.setText(year + "-" + (monthOfYear > 8 ? (monthOfYear+1) : ("0"+(monthOfYear+1))) + "-" + (dayOfMonth > 9 ? dayOfMonth : ("0"+dayOfMonth)));
            }     
    };

}
